﻿using QWManage.Model;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;

namespace QWManage.DAL
{
    public class UsersCustomersRDAL : SqlDAL
    {
        public UsersCustomersRDAL()
        {
            TableName = "QW_Users_Customers";
        }
        private void insert(string userID, string exuserID)
        {
            string sql = $"insert into {TableName} (UserID,ExuserID) values (@UserID,@ExuserID)";
            using (SqlConnection conn = new SqlConnection(SQLCON))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.Add(new SqlParameter("@UserID", userID));
                cmd.Parameters.Add(new SqlParameter("@ExuserID", exuserID));
                cmd.ExecuteNonQuery();
            }
        }

        private bool Exists(string userID, string exuserID)
        {
            string sql = $"select count(UserID) from {TableName} where UserID=@UserID and ExuserID=@ExuserID";
            using (SqlConnection conn = new SqlConnection(SQLCON))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.Add(new SqlParameter("@UserID", userID));
                cmd.Parameters.Add(new SqlParameter("@ExuserID", exuserID));
                int count = (int)cmd.ExecuteScalar();
                return count > 0;
            }
        }

        public void Add(List<RelationshipInfo> relationshipInfos)
        {
            for (int i = 0; i < relationshipInfos.Count; i++)
            {
                RelationshipInfo obj = relationshipInfos[i];
                if (Exists(obj.UserID, obj.ExuserID)) continue;
                insert(obj.UserID, obj.ExuserID);
            }
        }
    }
}
